package com.zmn.oms.task.job.comment;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.oms.business.interfaces.comment.OrderCommentBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.dto.comment.OrderCommentDTO;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * 类描述：定时评价内容
 *
 * @author lujia
 * @date 2019/02/12 17:58
 */
@LTS
@Slf4j
public class CommentJob {

    @Autowired
    OrderCommentService orderCommentService;
    @Autowired
    OrderCommentBService orderCommentBService;
    @Autowired
    OrderWorkService orderWorkService;

    private final static int DEFAULT_SCORE = 5;

    /**
     * 运行评价任务
     * 工单完成1周，若用户仍未评价，则系统自动默认评价,系统默认评价评星为：3星，评价内容为空
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_COMMENT)
    public Result runComment(Job job){
        String orderIdStr = job.getParam("orderId");
        Long orderId = Long.valueOf(orderIdStr);

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
            log.info("#comment# 退款单 无需自动评价");
            return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
        }

        OrderComment comment = orderCommentService.findCommentByKey(orderId);
        if (comment == null) {
            OrderCommentDTO commentDTO = new OrderCommentDTO();
            commentDTO.setWorkId(orderId);
            commentDTO.setOrderId(orderId);

            commentDTO.setOperatorPlat(orderWork.getPlatWork());
            commentDTO.setOperator("系统");
            commentDTO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            commentDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);

            commentDTO.setType(OrderConsts.COMMENT_TYPE_DEFAULT);
            commentDTO.setScore(DEFAULT_SCORE);

            try {
                orderCommentBService.saveComment(commentDTO);
            } catch (OmsBaseException e) {
                log.error(e.getMessage(), e);
            }

        }  else {
            log.info("#comment# 已评价不处理 ！");
        }

        log.info("#comment# 评价任务执行成功 ！");
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }
}
